package com.atguigu.yygh.util;

import com.atguigu.yygh.common.helper.HttpRequestHelper;
import com.atguigu.yygh.common.util.MD5;
import com.atguigu.yygh.exception.YyghException;
import com.atguigu.yygh.result.ResultCodeEnum;
import com.atguigu.yygh.service.HospitalSetService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * @author zr
 * @date 2021/12/14 13:53
 */
@Component
public class SignValidUtils {
    @Resource
    private HospitalSetService hospitalSetService;

    /**
     * 进行签名校验
     *
     * @param request
     * @return
     */
    public Map<String, Object> signValidation(HttpServletRequest request) {
        // 获取传递过来的医院信息
        Map<String, String[]> resultMap = request.getParameterMap();
        // 转换map
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(resultMap);
        // 获取医院系统传递过来的签名  签名进行MD5加密
        String hospSign = (String) paramMap.get("sign");
        if (StringUtils.isEmpty(hospSign)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        // 根据传递过来的医院编码 查询数据库 获取签名
        String hosCode = (String) paramMap.get("hoscode");
        if (StringUtils.isEmpty(hosCode)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        // 把数据库查询出来的医院签名  进行MD5加密
        String signKey = hospitalSetService.getHosCode(hosCode);
        String signKeyMD5 = MD5.encrypt(signKey);
        if (!Objects.equals(signKeyMD5, hospSign)) {
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
        return paramMap;
    }
}
